<template>
  <div>
    <!-- 搜索栏 -->

    <el-card id="search">
      <el-row>
        <el-col :span="20">
          <el-input placeholder="标题" v-model="searchModel.title" clearable>
          </el-input>
          <el-select
            v-model="searchModel.userId"
            placeholder="用户名"
            clearable
            v-if="name === 'admin'"
          >
            <el-option
              :label="item.username"
              :value="item.userId"
              v-for="item in userIdForm"
              :key="item.userId"
            ></el-option>
          </el-select>
          <el-select
            v-model="searchModel.billStatus"
            placeholder="票据状态"
            clearable
          >
            <el-option label="已审核" value="1"></el-option>
            <el-option label="未审核" value="2"></el-option>
            <el-option label="未通过" value="4"></el-option>
          </el-select>
          <el-button
            @click="getBillList"
            type="primary"
            round
            icon="el-icon-search"
            >查询</el-button
          >
        </el-col>
        <el-col :span="4" align="right" v-if="name != 'admin'">
          <!-- <el-button
            type="success"
            icon="el-icon-document"
            circle
           
            alt="草稿箱"
          ></el-button> -->
          <el-button type="success" round  style="margin-right: 20px"
          @click="searchDraft">草稿箱</el-button>
          <el-button
            @click="openEditUi(null)"
            type="primary"
            icon="el-icon-plus"
            circle
          ></el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 结果列表 -->
    <el-card>
      <el-table :data="billList" style="width: 100%">
        <el-table-column label="序号">
          <template slot-scope="scope">
            <!-- 作用域插槽 -->
            <!-- (pageNum-1)*pageSize + index +1 -->
            {{
              (searchModel.pageNum - 1) * searchModel.pageSize +
              scope.$index +
              1
            }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="id" label="票据ID" width="180">
        </el-table-column> -->
        <el-table-column prop="title" label="票据标题"> </el-table-column>
        <el-table-column prop="userName" label="用户名" v-if="name === 'admin'">
        </el-table-column>
        <el-table-column prop="description" label="票据描述"> </el-table-column>
        <el-table-column prop="statusId" label="票据状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.statusId == 1">已审核</el-tag>

            <el-tag v-else-if="scope.row.draftFlag == 1" type="success"
              >待提交</el-tag
            >
            <el-tag v-else-if="scope.row.statusId == 4" type="danger">未通过</el-tag>
            <el-tag v-else type="info">未审核</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              size="mini"
              @click="openEditUi(scope.row.id)"
              v-if="name != 'admin' && scope.row.draftFlag == 1"
            ></el-button> -->
            <el-button
              type="primary"
              round
              size="mini"
              @click="openEditUi(scope.row.id)"
              v-if="name != 'admin' && (scope.row.draftFlag == 1 || scope.row.statusId === 4)"
              >编辑</el-button
            >
            <!-- <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              size="mini"
              @click="deleteUser(scope.row)"
            ></el-button> -->
            <!-- <el-button
              type="info"
              icon="el-icon-zoom-in"
              circle
              size="mini"
              @click="openDetail(scope.row.id)"
            ></el-button> -->
            <el-button
              type="info"
              round
              size="mini"
              @click="openDetail(scope.row.id)"
              >查看</el-button
            >
            <!-- <el-button
              type="warning"
              icon="el-icon-edit-outline"
              circle
              size="mini"
              @click="openAudit(scope.row)"
              v-if="
                name == 'admin' &&
                scope.row.statusId != 1 &&
                scope.row.draftFlag == 0
              "
            ></el-button> -->
            <el-button
              type="warning"
              round
              size="mini"
              @click="openAudit(scope.row)"
              v-if="
                name == 'admin' &&
                scope.row.statusId != 1 &&
                scope.row.draftFlag == 0 && scope.row.statusId !== 4
              "
              >审核</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchModel.pageNum"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="searchModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 审核票据对话框 -->
    <el-dialog
      @close="clearFormAu"
      title="审核票据"
      :visible.sync="dialogFormVisibleAu"
      width="40%"
    >
      <el-form :model="auditForm">
        <!-- <el-form-item
          label="用户名"
          :label-width="formLabelWidth"
          prop="username"
        >
          <el-input v-model="userForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          :label-width="formLabelWidth"
          prop="password"
        >
          <el-input
            v-model="userForm.password"
            autocomplete="off"
            show-password
          ></el-input>
        </el-form-item> -->
        <!-- <el-form-item
          label="状态"
          :label-width="formLabelWidth"
          v-if="userForm.id != null || userForm.id != undefined"
        >
          <el-switch
            v-model="userForm.statusId"
            :active-value="1"
            :inactive-value="2"
          >
          </el-switch>
        </el-form-item> -->
        <el-form-item label="票据ID :" :label-width="formLabelWidth">
          <span>{{ auditForm.id }}</span>
        </el-form-item>
        <el-form-item label="票据标题 :" :label-width="formLabelWidth">
          <span>{{ auditForm.title }}</span>
        </el-form-item>
        <el-form-item label="用户ID :" :label-width="formLabelWidth">
          <span>{{ auditForm.userId }}</span>
        </el-form-item>
        <el-form-item label="票据描述 :" :label-width="formLabelWidth">
          <span>{{ auditForm.description }}</span>
        </el-form-item>
        <el-form-item label="票据状态 :" :label-width="formLabelWidth">
          <span
            ><el-tag v-if="auditForm.statusId == 1">已审核</el-tag>
            <el-tag v-else-if="auditForm.draftFlag == 1" type="success"
              >待提交</el-tag
            >
            <el-tag v-else-if="auditForm.statusId == 4" type="danger">未通过</el-tag>
            <el-tag v-else type="info">未审核</el-tag></span
          >
        </el-form-item>
        <el-form-item label="附件信息:" :label-width="formLabelWidth">
          <span v-for="(file, index) in auditForm.files" :key="index"
            >文件名 : {{ file.fileName }} <br />文件路径 :
            {{ file.filePath }}</span
          >
        </el-form-item>
        <el-form-item label="创建时间 :" :label-width="formLabelWidth">
          <span>{{ auditForm.createdAt }}</span>
        </el-form-item>
        <el-form-item label="审核状态" :label-width="formLabelWidth">
          <el-select
            v-model="auditForm.audit"
            placeholder="审核状态"
            clearable
          >
            <el-option label="通过" value=1></el-option>
            <el-option label="退回" value=4></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核意见" :label-width="formLabelWidth">
          <el-input v-model="auditForm.comment" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleAu = false">取 消</el-button>
        <el-button type="primary" @click="auditBill">审 核</el-button>
      </div>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      @close="clearForm"
      :title="title"
      :visible.sync="dialogFormVisible"
      width="40%"
    >
      <el-form :model="billForm" ref="billFormRef">
        <el-form-item
          label="票据标题"
          :label-width="formLabelWidth"
          prop="title"
        >
          <el-input v-model="billForm.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="票据描述" :label-width="formLabelWidth">
          <el-input
            v-model="billForm.description"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item
          label="状态"
          :label-width="formLabelWidth"
          v-if="userForm.id != null || userForm.id != undefined"
        >
          <el-switch
            v-model="userForm.statusId"
            :active-value="3"
            :inactive-value="4"
          >
          </el-switch>
        </el-form-item> -->
        <!-- <el-form-item
          label="电子邮箱"
          :label-width="formLabelWidth"
          prop="email"
        >
          <el-input v-model="userForm.email" autocomplete="off"></el-input>
        </el-form-item> -->
        <el-form-item
          label="附件上传"
          :label-width="formLabelWidth"
          v-if="billForm.id === null || billForm.id === undefined"
        >
          <el-upload
            ref="mYupload"
            class="upload"
            action="http://localhost:8080/api/file/upload"
            :headers="{ 'bill-token': token }"
            :on-success="handleSuccess"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip"></div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="info" v-if="draftFlagV" @click="draftBill"
          >保 存</el-button
        >
        <el-button type="primary" @click="saveBillA">{{ tip }}</el-button>
      </div>
    </el-dialog>

    <el-dialog title="票据详情" :visible.sync="dialogFormVisibleA">
      <el-form :model="detailForm">
        <el-form-item label="票据ID :" :label-width="formLabelWidth">
          <span>{{ detailForm.id }}</span>
        </el-form-item>
        <el-form-item label="票据标题 :" :label-width="formLabelWidth">
          <span>{{ detailForm.title }}</span>
        </el-form-item>
        <el-form-item label="用户ID :" :label-width="formLabelWidth">
          <span>{{ detailForm.userId }}</span>
        </el-form-item>
        <el-form-item label="票据描述 :" :label-width="formLabelWidth">
          <span>{{ detailForm.description }}</span>
        </el-form-item>
        <el-form-item label="票据状态 :" :label-width="formLabelWidth">
          <span
            ><el-tag v-if="detailForm.statusId == 1">已审核</el-tag>
            <el-tag v-else-if="detailForm.draftFlag == 1" type="success"
              >待提交</el-tag
            >
            <el-tag v-else type="danger">未审核</el-tag></span
          >
        </el-form-item>
        <el-form-item label="附件信息:" :label-width="formLabelWidth">
          <span v-for="(file, index) in detailForm.files" :key="index"
            >文件名 : {{ file.fileName }} <br />文件路径 :
            {{ file.filePath }}</span
          >
        </el-form-item>
        <el-form-item label="创建时间 :" :label-width="formLabelWidth">
          <span>{{ detailForm.createdAt }}</span>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import billApi from "@/api/billManage";
import userApi from "@/api/userManage";
import { mapGetters } from "vuex";
import store from "@/store";
export default {
  computed: {
    ...mapGetters(["name","role"]),
  },
  data() {
    return {
      userIdForm: [],
      dialogFormVisibleAu: false,
      token: store.getters.token,
      auditForm: {},
      draftFlagV: false,
      tip: "",
      detailForm: {},
      dialogFormVisibleA: false,
      formLabelWidth: "130px",
      billForm: {
        draftFlag: 0,
        files: [],
      },
      message: "",
      title: "",
      dialogFormVisible: false,
      total: 0,
      searchModel: {
        pageNum: 1,
        pageSize: 10,
        // statusId: "1",
      },
      billList: [],
    };
  },
  methods: {
    clearFormAu() {
      this.auditForm = {};
    },
    auditBill() {
      // console.log(this.auditForm);

      billApi.auditBill(this.auditForm).then((response) => {
        if (response.success !== false) {
          this.$message({
            showClose: true,
            message: "审核成功",
            type: "success",
          });

          // 关闭对话框
          this.dialogFormVisibleAu = false;

          //刷新表格
          this.getBillList();
        }
      });
    },
    handleSuccess(response, file, fileList) {
      // 这里可以获取服务器返回的数据
      // console.log(response);
      // 可以根据返回的数据进行后续操作，比如更新UI或处理业务逻辑
      let newFile = {
        fileName: response.data.fileName,
        filePath: response.data.filePath,
        uploadBy: response.data.uploadBy,
      };
      this.billForm.files.push(newFile);
      // console.log(this.billForm);
    },
    openAudit(bill) {
      this.dialogFormVisibleAu = true;
      billApi.getBillById(bill.id).then((response) => {
        this.auditForm = response.data;
        // 创建一个新的Date对象
        const date = new Date(this.auditForm.createdAt);
        // 使用toISOString方法并截取日期部分来格式化日期
        const formattedDate = date.toISOString().split("T")[0];
        // 将格式化后的日期赋值给user对象的createdAt属性
        this.auditForm.createdAt = formattedDate;
        
      });

      // this.auditForm.id = bill.id;
      // this.auditForm.audit = 1;
      // console.log(this.auditForm);

      // this.auditForm.title = bill.title;
      // this.auditForm.description = bill.description;
      // this.auditForm.userId = bill.userId;
      // this.auditForm.createdAt = bill.createdAt;
      // this.auditForm.statusId = bill.statusId;
      // this.auditForm.files = bill.files;
    },
    searchDraft() {
      billApi.getBillList(this.searchModel).then((response) => {
        // 首先过滤掉draftFlag等于1的记录
        this.billList = response.records
          .filter((bill) => bill.draftFlag === 1)
          .map((bill) => {
            // 创建一个新的Date对象
            const date = new Date(bill.createdAt);
            // 使用toISOString方法并截取日期部分来格式化日期
            const formattedDate = date.toISOString().split("T")[0];
            // 将格式化后的日期赋值给bill对象的createdAt属性
            bill.createdAt = formattedDate;
            // 返回更新后的bill对象
            return bill;
          });
        this.total = response.total;
      });
    },
    draftBill() {
      this.billForm.draftFlag = 1;
      this.message = "保存草稿成功";
      this.saveBill();
    },
    saveBillA() {
      this.billForm.draftFlag = 0;
      this.message = "提交票据成功";
      this.saveBill();
    },
    openDetail(id) {
      billApi.getBillById(id).then((response) => {
        this.detailForm = response.data;
        // console.log(response);

        // 创建一个新的Date对象
        const date = new Date(this.detailForm.createdAt);
        // 使用toISOString方法并截取日期部分来格式化日期
        const formattedDate = date.toISOString().split("T")[0];
        // 将格式化后的日期赋值给user对象的createdAt属性
        this.detailForm.createdAt = formattedDate;
        // 返回更新后的user对象
        this.dialogFormVisibleA = true;
      });
    },
    saveBill() {
      //提交时表单验证
      this.$refs.billFormRef.validate((valid) => {
        if (valid) {
          //验证通过提交后台
          billApi.saveBill(this.billForm).then((response) => {
            //成功提示

            if (response.success !== false) {
              this.$message({
                showClose: true,
                message: this.message,
                type: "success",
              });

              // 关闭对话框
              this.dialogFormVisible = false;

              //刷新表格
              this.getBillList();
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    clearForm() {
      this.billForm = {};
      this.$refs["mYupload"].clearFiles();
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.searchModel.pageNum = 1;
      this.getBillList();
    },
    handleCurrentChange(pageNum) {
      this.searchModel.pageNum = pageNum;
      this.getBillList();
    },
    openEditUi(id) {
      if (id === null) {
        this.title = "新增票据";
        this.draftFlagV = true;
        this.tip = "提 交";
        this.message = "新增票据成功";
      } else {
        this.title = "修改票据";
        this.draftFlagV = true;
        this.tip = "提 交";
        this.message = "提交票据成功";
        //根据id
        billApi.getBillById(id).then((response) => {
          this.billForm = response.data;
          console.log(this.billForm);
        });
        // console.log(this.userForm);
      }
      this.dialogFormVisible = true;
    },
    getBillList() {
      billApi.getBillList(this.searchModel).then((response) => {
        this.billList = response.records
          // .filter((bill) => bill.userId !== 1)
          .map((bill) => {
            // 创建一个新的Date对象
            const date = new Date(bill.createdAt);
            // 使用toISOString方法并截取日期部分来格式化日期
            const formattedDate = date.toISOString().split("T")[0];
            // 将格式化后的日期赋值给user对象的createdAt属性
            bill.createdAt = formattedDate;
            // 返回更新后的user对象
            return bill;
          });
        this.total = response.total;
      });
    },
  },
  created() {
    // console.log(this.token);

    this.getBillList();
    // console.log(this.role);
    
    if (this.role.includes("admin"))
      userApi.getVoList().then((response) => {
        this.userIdForm = response.data;
        // console.log(this.userIdForm);
      });
  },
};
</script>

<style>
#search .el-input {
  width: 200px;
  margin-right: 15px;
}
.el-dialog .el-input {
  width: 85%;
}
.el-pagination {
  display: flex;
  flex-direction: row;
  justify-content: center;
}
.upload {
  margin-left: 0px;
}
</style>